package tv.acgn.advertisement.search.index;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
import org.springframework.stereotype.Component;

/**
 * @author : junG
 * @program : advertisement-ad-search-index
 * @description : 索引服务
 * @date : 2019-07-14 20:56
 **/

@Component
public class IndexDataTable implements ApplicationContextAware, PriorityOrdered {

    private static ApplicationContext applicationContext;

    public static final Map<Class, Object> dataTableMap = new ConcurrentHashMap<>(50);

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        IndexDataTable.applicationContext = applicationContext;
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }

    public static <T> T of(Class<T> clazz) {
        T instance = (T)dataTableMap.get(clazz);
        if (null != instance) {
            return instance;
        }
        T t = IndexDataTable.getBean(clazz);
        dataTableMap.put(clazz, t);
        return t;
    }

    private static <T> T getBean(String beanName) {
        return (T)applicationContext.getBean(beanName);
    }

    private static <T> T getBean(Class clazz) {
        return (T)applicationContext.getBean(clazz);
    }
}
